﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace SubtitleDownloader.Providers
{
	public class Subscenter : ISubtitleProvider
	{
		public string Name
		{
			get { return "Subscenter"; }
		}

		public IEnumerable<SubtitleItem> GetSubtitles(VideoItem videoItem)
		{
			Uri uri;
			if (Uri.TryCreate(new Uri("http://www.subscenter.org/he/subtitle/series/"),
				String.Format("{0}/{1}/{2}", FixSeriesName(videoItem.Name), videoItem.Season, videoItem.Episode), out uri)) {
				var res = Utils.GetHtml(uri);
				if (res != null) {
					var matches = Regex.Matches(res, @"\""id\"":\s?(?<id>\d+?)\,[^{]*?\""key\"":\s?\""(?<key>.*?)\""\,[^{]*?\""subtitle_version\""\:\s?\""(?<name>.*?)\""\,",
						RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase);
					foreach (Match m in matches) {
						Uri url;
						if (!Uri.TryCreate(new Uri("http://www.subscenter.org/subtitle/download/he/"),
							String.Format("{0}/?v={1}&key={2}", m.Groups["id"].Value, m.Groups["name"].Value, m.Groups["key"].Value), out url))
							continue;
						yield return new SubtitleItem(m.Groups["name"].Value, url);
					}
				}
			}
		}

		private string FixSeriesName(string name)
		{
			if (name == null)
				return name;
			return name.Replace(" ", "-");
		}
	}
}
